package com.ita.acmsystem.merchant.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ita.acmsystem.merchant.entity.Foods;
import com.ita.acmsystem.merchant.entity.Merchant;
import com.ita.acmsystem.merchant.entity.mock.ProtocalMock;
import com.ita.acmsystem.merchant.service.IFoodService;
import com.ita.acmsystem.merchant.service.impl.FoodServiceImpl;
import com.ita.acmsystem.merchant.util.SimpleJsonUtil;

/**
 * Servlet implementation class AjaxQueryFoodServlet
 */
public class AjaxQueryFoodServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private IFoodService foodService = new FoodServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AjaxQueryFoodServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		queryFood(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		queryFood(request, response);
	}

	private void queryFood(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		Merchant user = (Merchant) session.getAttribute("user");

//		List<Foods> foodsList = foodService.getAllFoods();
		List<Foods> foodsList = foodService.getFoodsByMerchantId(user.getMerchantId());

		ProtocalMock protocal = new ProtocalMock();

		String status = null, msg = null;
		if (foodsList == null) {

			status = "error";
			msg = "database query error!";

			protocal.setStatus("error");
			protocal.setMessage("database query error!");

		} else {
			status = "success";

			protocal.setStatus("success");
		}
		JSONObject jsonObject = new JSONObject();
		ObjectMapper mapper = new ObjectMapper();
		String data = mapper.writeValueAsString(foodsList);
		try {
			jsonObject.put("status", status);
			jsonObject.put("msg", msg);
			jsonObject.put("data", data);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// System.out.println(data);
		protocal.setData(foodsList);

		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		// writer.write(jsonObject.toString());
		writer.write(SimpleJsonUtil.format(protocal));
	}

}
